import re
from rest_framework import serializers
from .models import Address

class AddressSerializer(serializers.ModelSerializer):

    province_id = serializers.CharField(write_only=True)
    city_id = serializers.CharField(write_only=True)
    district_id = serializers.CharField(write_only=True)
    province = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    # token = serializers.CharField(write_only=True)

    class Meta:
        model = Address
        fields = ('receiver','province','city','district','place','mobile','tel','email','city_id','province_id','district_id',
                  'id','title')

    def validate(self, attrs):

        if not re.match(r'1[3-9]\d{9}',attrs['mobile']):
            raise serializers.ValidationError({'message':'手机号格式不正确.'})

        return attrs

    def create(self, validated_data):

        user = self.context['request'].user

        validated_data['user'] = user
        address = Address.objects.create(**validated_data)


        return address



